package caat.framework;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import caat.application.dao.LogsDAO;
import caat.framework.utils.AppUtils;



public class AppAction {
//	private final static ResourceBundle bundle = ReadFileResourceBundle
//			.getConnectionSql(fileResourceName);
//	private final static String driverConnection = bundle
//			.getString("appstore.database.driver");
//	private final static String databaseUrlConnection = bundle
//			.getString("appstore.database.databaseUrl");
//	private final static String usernameConnection = bundle
//			.getString("appstore.database.username");
//	private final static String passwordConnection = bundle
//			.getString("appstore.database.password");

	protected Connection getConnection() throws ClassNotFoundException,
			SQLException {
		Connection connection = null;
		try {
			//get key file resource 
			AppUtils appUtil = new AppUtils();
			ResourceBundle rb  = appUtil.getConnectionSql(AppConstants.FILE_DATABASE);			
			Class.forName(rb.getString(AppConstants.DRIVER_CONNECTION));
			connection = DriverManager.getConnection(rb.getString(AppConstants.DATABASE_URL),
					rb.getString(AppConstants.USER_CONNECTION), rb.getString(AppConstants.PASS_CONNECTION));
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return connection;
	}

	protected void close(Connection conn) {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            conn = null;
        }
    }
    // close ResultSet

    protected void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                rs = null;
            }

        }
    }

    // close PreparedStatement

    protected void close(PreparedStatement pstmt) {
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                pstmt = null;
            }

        }
    }

    // close Statement

    protected void close(Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                stmt = null;
            }
        }
    }

//    protected void saveError(HttpServletRequest request, String key) {
//        ActionErrors errors = new ActionErrors();
//        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(key));
//        saveErrors(request, errors);
//    }
//
//    protected void saveError(HttpServletRequest request, String key,
//                             String value0) {
//        ActionErrors errors = new ActionErrors();
//        errors.add(ActionErrors.GLOBAL_ERROR, new ActionError(key, value0));
//        saveErrors(request, errors);
//    }
//
//    protected void saveError(HttpServletRequest request, String key,
//                             String value0, String value1) {
//        ActionErrors errors = new ActionErrors();
//        errors.add(ActionErrors.GLOBAL_ERROR,
//                   new ActionError(key, value0, value1));
//        saveErrors(request, errors);
//    }
//
//    protected void saveError(HttpServletRequest request, String key,
//                             String value0, String value1, String value2) {
//        ActionErrors errors = new ActionErrors();
//        errors.add(ActionErrors.GLOBAL_ERROR,
//                   new ActionError(key, value0, value1, value2));
//        saveErrors(request, errors);
//    }
//
//    protected void saveError(HttpServletRequest request, String key,
//                             String value0, String value1, String value2,
//                             String value3) {
//        ActionErrors errors = new ActionErrors();
//        errors.add(ActionErrors.GLOBAL_ERROR,
//                   new ActionError(key, value0, value1, value2, value3));
//        saveErrors(request, errors);
//    }
//
//    protected void saveError(HttpServletRequest request, TTSPException ex) {
//        ServletContext context = servlet.getServletContext();
//        HashMap errorMap =
//            (HashMap)context.getAttribute(AppKeys.ERROR_LIST_APPLICATION_KEY);
//        String msgError = ex.getMessage(errorMap);
//        ActionErrors errors = new ActionErrors();
//        errors.add(ActionErrors.GLOBAL_ERROR,
//                   new ActionError("errors", msgError));
//        saveErrors(request, errors);
//    }
//
//    protected void saveError2(HttpServletRequest request, TTSPException ex) {
//        ServletContext context = servlet.getServletContext();
//        HashMap errorMap =
//            (HashMap)context.getAttribute(AppKeys.ERROR_LIST_APPLICATION_KEY);
//        String strErrorHeader =
//            ex.getMoTaLoi(errorMap).replace(":", "").replace("{0}",
//                                                             "").replace("{1}",
//                                                                         "").replace("{2}",
//                                                                                     "");
//        String strErrorDetail = ex.getMessage(errorMap);
//
//        ActionErrors errors = new ActionErrors();
//        errors.add(ActionErrors.GLOBAL_ERROR,
//                   new ActionError("errors", strErrorHeader, strErrorDetail));
//        saveErrors(request, errors);
//    }
//
//    protected void close(Connection conn) {
//        try {
//            if (conn != null && !conn.isClosed()) {
//                conn.close();
//            }
//        } catch (SQLException e) {
//            e.printStackTrace();
//        } finally {
//            conn = null;
//        }
//    }
//    // close ResultSet
//
//    protected void close(ResultSet rs) {
//        if (rs != null) {
//            try {
//                rs.close();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            } finally {
//                rs = null;
//            }
//
//        }
//    }
//
//    // close PreparedStatement
//
//    protected void close(PreparedStatement pstmt) {
//        if (pstmt != null) {
//            try {
//                pstmt.close();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            } finally {
//                pstmt = null;
//            }
//
//        }
//    }
//
//    // close Statement
//
//    protected void close(Statement stmt) {
//        if (stmt != null) {
//            try {
//                stmt.close();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            } finally {
//                stmt = null;
//            }
//        }
//    }
//
//    protected String populateBeanToXml(Object vo, String strValueObject,
//                                       String rootElement) throws Exception {
//
//        XStream xstream = new XStream();
//
//        xstream.alias(rootElement, Class.forName(strValueObject));
//
//        String xml = xstream.toXML(vo);
//
//        return xml;
//    }
//
//    /**
//     * @see: Kiem tra quyen cua User tren action
//     * */
//    protected boolean checkPermissionOnFunction(HttpServletRequest request,
//                                                String strAction) throws Exception {
//        HttpSession session = request.getSession();
//        if ("".equals(strAction))
//            return false;
//        Collection colCNang =
//            (Collection)session.getAttribute(AppConstants.APP_CHUC_NANG_LIST_SESSION);
//        if (null == colCNang)
//            return false;
//        Iterator iter = colCNang.iterator();
//        ChucNangVO cnangVO = null;
//        while (iter.hasNext()) {
//            cnangVO = (ChucNangVO)iter.next();
//            if (strAction.equalsIgnoreCase(cnangVO.getKy_hieu_cnang())) {
//                return true;
//            }
//        }
//        return false;
//    }
//
    /**
     * @see: Ghi log truy cap doi voi moi action
     * */
    protected void saveVisitLog(Connection conn, String strUserID,
                                String strAction, String strIP,
                                String strDes) throws Exception {
    	LogsDAO logDAO = new LogsDAO(conn);
    	logDAO.saveVisitLog(strUserID, strAction, strIP, strDes);
    }
    protected void displayError(String errorSummary,String errorDetail){
    	FacesContext context = FacesContext.getCurrentInstance();
	    FacesMessage message = new FacesMessage();
	    message.setSeverity(FacesMessage.SEVERITY_ERROR);
	    message.setSummary(errorSummary);
	    message.setDetail(errorDetail);
	    context.addMessage("tutorialForm:name",message);    	
    }   
//
//    /**
//     * @see: Lay tham so he thong
//     * @param:
//     * @return: Tra ve danh sach tham so he thong
//     * */
//    protected Collection getThamSoHThong() {
//        ServletContext context = servlet.getServletContext();
//        return (Collection)context.getAttribute(AppKeys.PARAM_LIST_APPLICATION_KEY);
//    }
//
//    /**
//     * @see: Lay tham so he thong
//     * @param: truyen vao ten TSo
//     * @return: Tra ve gia tri tham so he thong
//     * */
//    protected String getThamSoHThong(String strTenTSo) {
//        ServletContext context = servlet.getServletContext();
//        ThamSoHThong tso = new ThamSoHThong();
//        Collection collThamSoList =
//            (Collection)context.getAttribute(AppKeys.PARAM_LIST_APPLICATION_KEY);
//        return tso.getThamSoHThong(strTenTSo, collThamSoList);
//    }
//
//    /**
//     * @see: Lay tham so he thong rieng cua moi kho bac
//     * @param: Truyen vao ten TSo va ID cua KB (ID cua bang SP_DM_HTKB)
//     * @return: Tra ve gia tri TSo he thong
//     * */
//    protected String getThamSoHThong(String strTenTSo, Long nKBacID) {
//        ServletContext context = servlet.getServletContext();
//        ThamSoHThong tso = new ThamSoHThong();
//        Collection collThamSoList =
//            (Collection)context.getAttribute(AppKeys.PARAM_LIST_APPLICATION_KEY);
//        return tso.getThamSoHThong(strTenTSo, nKBacID, collThamSoList);
//    }
//
//    /**
//     * @see: Lay tham so he thong rieng cua moi kho bac
//     * @param: Truyen vao ten TSo va ID cua KB (ID cua bang SP_DM_HTKB)
//     * @return: Tra ve gia tri TSo he thong
//     * */
//    protected UserVO getUserInfo(String strUserID) throws Exception {
//        Connection conn = null;
//        try {
//            conn = getConnection();
//            UserDAO ssDAO = new UserDAO(conn);
//            Vector vParams = new Vector();
//            vParams.add(new Parameter(strUserID, true));
//            UserVO vo = ssDAO.getUser("a.id = ?", vParams);
//            return vo;
//        } finally {
//            close(conn);
//        }
//    }
//
//    protected List getDSachCNang(HttpServletRequest request,
//                                 String strAction) {
//        List lstCNang = null;
//        if ("".equals(strAction))
//            return lstCNang;
//        HttpSession session = request.getSession();
//        Collection colCNang =
//            (Collection)session.getAttribute(AppConstants.APP_CHUC_NANG_LIST_SESSION);
//        Iterator iter = colCNang.iterator();
//        ChucNangVO cnangVO = null;
//        //Lay ID chuc nang cha
//        boolean checkExist = false;
//        while (iter.hasNext()) {
//            cnangVO = (ChucNangVO)iter.next();
//            if (strAction.equalsIgnoreCase(cnangVO.getKy_hieu_cnang())) {
//                checkExist = true;
//                break;
//            }
//        }
//        if (!checkExist)
//            return lstCNang;
//        long nCNangChaID = cnangVO.getId().longValue();
//        //Lay cac chuc nang con
//        iter = colCNang.iterator();
//        lstCNang = new ArrayList();
//        while (iter.hasNext()) {
//            cnangVO = (ChucNangVO)iter.next();
//            if (cnangVO.getCnang_cha() == null)
//                continue;
//            if (nCNangChaID == cnangVO.getCnang_cha().longValue()) {
//                lstCNang.add(cnangVO);
//            }
//        }
//        return lstCNang;
//    }
}
